"""Some utility functions for morsesender.py."""

import time
import logging as mylog
import functools


mylog.basicConfig(
    level=mylog.DEBUG,
    format='%(asctime)s %(levelname)s %(message)s',
    datefmt='%H:%M:%S'
)


def prnt(*s):
    """Prints without a newline and flushes."""

    print(*s, end='', flush=True)


def timeit(func):
    """Decorator to time functions."""

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        t0 = time.time()
        ret = func(*args, **kwargs)
        t1 = time.time()
        mylog.info(f'{func.__name__} took {int(t1-t0)} seconds')
        return ret

    return wrapper


def msg2morse(msg):
    """Encodes an ASCII message (capitals and spaces only) to morse."""

    morse = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.',
             'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---',
             'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---',
             'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-',
             'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--',
             'Z': '--..', '0': '-----', '2': '..---', ' ': 'S'}
    code = ' '.join(morse[ch] for ch in msg).replace(' S ', 'S')
    return code


def new_brightness():
    """Returns a PWM value suitable for the time of day."""

    h = time.localtime().tm_hour
    if h >= 9 and h < 16:
        return(6)           # day
    else:
        return(1)           # night
